package com.software.controller;


import com.software.dao.InvoiceDAO;
import com.software.entity.Invoice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

@WebServlet("/addInvoice")
public class AddInvoice extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码的方式
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取表单参数
        //开具人
        String issuerName = request.getParameter("issuerName");
        //开具金额
        float totalAmount = Float.parseFloat(request.getParameter("totalAmount"));

        // 创建Invoice对象并设置属性
        Invoice invoice = new Invoice();
        invoice.setIssuerName(issuerName);
        invoice.setTotalAmount(totalAmount);
        //发票号  随机十二位
        String invoiceNumber = "";
        Random random=new Random();
        for(int i =0;i<12;i++){
            if(i==0){
                //首位不能为0且数字取值区间为 [1,9]
                invoiceNumber+=(random.nextInt(9)+1);
            }else{
                //其余位的数字的取值区间为 [0,9]
                invoiceNumber+=random.nextInt(10);
            }
        }
        invoice.setInvoiceNumber(invoiceNumber);
        //开具日期
        invoice.setIssueDate(new java.sql.Timestamp(new Date().getTime()));
        System.out.println(invoice.toString());




        // 调用DAO层方法将Invoice对象插入数据库
        InvoiceDAO.addInvoice(invoice);

        // 重定向到展示发票信息的页面
        response.sendRedirect("/exam/index.jsp");
    }
}
